package cn.tedu.charging.order.emqx;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 避免业务开发直接解除底层api
 * 封装底层client客户端 尽可能让业务 更兼容生产者方法
 */
@Component
@Slf4j
public class MqttProducer {
    @Autowired
    private MqttClient mqttClient;
    /**
     * producer 提供了满足 兼容业务的生产发送的方法
     * String topic: 消息向哪个topic发送
     * String message: 发送消息 业务需要转化json
     * return boolean: 发送成功返回true 发送失败返回false
     */
    public boolean sendMessage(String topic,String message){
        log.debug("向主题:{},发送消息:{}",topic,message);
        try {
            mqttClient.publish(topic,message.getBytes(StandardCharsets.UTF_8),0,false);
        } catch (MqttException e) {
            log.error("向主题:{},发送消息:{}失败",topic,message,e);
            return false;
        }
        return true;
    }
}



















